package org.ucas.kgraph.entity;

import com.google.common.collect.Lists;
import org.hibernate.annotations.*;

import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 账号类,只记录用户最核心的信息
 *
 * @author suemi
 */
@Entity
@Table
public class Account extends IdEntity {

  @NotNull
  @OneToOne(optional = false)
  @JoinColumn(nullable = false, name = "profile_id", referencedColumnName = "id")
  private UserProfile userProfile;

  @NotNull
  private String name;

  @NotNull
  private String password;

  private String salt;

  @Transient
  private String plainPassword;
  
  @ManyToMany(fetch=FetchType.EAGER)
  @JoinTable(name="ss_user_role",joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
  @Fetch(FetchMode.SUBSELECT)
  @OrderBy("id ASC")
  @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
  private List<Role> roleList= Lists.newArrayList();

  @Column(nullable = false,columnDefinition = "TINYINT(1)")
  private boolean disabled = false;

  public UserProfile getUserProfile() {
    return userProfile;
  }

  public void setUserProfile(UserProfile userProfile) {
    this.userProfile = userProfile;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public boolean isDisabled() {
    return disabled;
  }

  public void setDisabled(boolean disabled) {
    this.disabled = disabled;
  }

  public String getPlainPassword() {
    return plainPassword;
  }

  public void setPlainPassword(String plainPassword) {
    this.plainPassword = plainPassword;
  }

  public String getSalt() {
    return salt;
  }

  public void setSalt(String salt) {
    this.salt = salt;
  }
  
  
  public List<Role> getRoleList() {
	return roleList;
  }

  public void setRoleList(List<Role> roleList) {
	this.roleList = roleList;
  }

  @Transient
  public Set<String> getRolesName() {
      List<Role> roles = getRoleList();
      Set<String> set = new HashSet<String>();
      for (Role role : roles) {
          set.add(role.getName());
      }
      return set;
  }

}
